/**
 * @name: findSiblingIds
 * @description: 获取传入id的兄弟节点
 * @param {Array} list //树形机构数据
 * @param {String} id //需要查找的id
 * @return {Array} //返回兄弟节点
 */
function findSiblingIds(list, id) {
  let node;
  for (let i in list) {
    if (list[i].id === id) {
      return list.filter((v) => v.id !== id);
    }
    if (list[i].children?.length > 0) {
      node = findSiblingIds(list[i].children, id);
      if (node) return node.filter((v) => v.id !== id);
    }
  }
  return node;
}

function addStationName(list) {
  list.forEach((item) => {
    if (item.level == 1) {
      item.label = item.orgName;
      item.id = item.orgId;
    }
    if (item.level == 2) {
      item.label = item.stationName;
      item.id = item.stationId;
    }
    if (item.level == 3) {
      item.label = item.unitsName;
      item.id = item.unitsId;
    }

    if (item.children) {
      addStationName(item.children);
    }
  });
  return list;
}

// 传入一个id获取它父级的id
function getAllParentNodes(list, id) {
  if (list.length === 0 || !list) return [];
  let node;

  for (let i in list) {
    if (list[i].id === id) {
      return [list[i]].filter((v) => v.id !== id);
    }
    if (list[i].children?.length > 0) {
      node = getAllParentNodes(list[i].children, id);
      if (node) return node.concat(list[i]).filter((v) => v.id !== id);
    }
  }
  return node;
}

import { Message } from "element-ui";

import { queryTreeData } from "@/api/common.js";

//引入VueOfficePdf组件
import * as XLSX from "xlsx";
import LuckyExcel from "luckyexcel";
// 导出
import { exportFn } from "@/utils/exportTable.js";

import { queryTable } from "@/api/firstAPI.js";

import { titleData, detailData } from "./data";
import { doc } from "docx-preview"; //引入renderAsync 方法

import { echartsData } from "./data";
import { forEach } from "lodash";

export default {
  name: "LabProjectIndex",
  data() {
    let yesOrNoList = {
      0: "否",
      1: "是",
    };

    return {
      queryTable,
      titleData: titleData,
      // getWindPowerList,
      formData: new FormData(),
      // key: 1,
      excelData: [],
      columns: [],
      pdf: "", //设置文档地址
      getFrom: {}, //每行的数据
      dispatchList: [], //调度
      stationTypeLists: [], //类型
      adjustRegulationLists: [], //上下调投入分类下拉框的数据
      voltageLevelLists: [], //电压等级下拉框的数据
      addDialogVisibleTitle: "新增",
      id: 0,
      dataTree: [],
      currentLivingId: "",
      form: {
        queryTime: this.dateFormat(new Date().getTime()),
        // 馈线id
        feederId: "",
        page: {
          pageIndex: 1,
          pageSize: 10,
        },
      },

      isYes: [
        {
          label: "是",
          value: 1,
        },
        {
          label: "否",
          value: 0,
        },
      ],

      defaultProps: {
        children: "children",
        label: "label",
      },
      queryDetailParam: {
        substationId: "1001",
        testDate: "",
        feederId: "",
      },
      operate: "add",
      testNumberList: [], //测试序号
      isYes: [
        {
          label: "是",
          value: 1,
        },
        {
          label: "否",
          value: 0,
        },
      ],
      headList: [
        // {
        //   name: '所属调度',
        //   value: 'regulationOrgName',
        //   noSort: true,
        // },
        // { name: '类型', value: 'stationTypeName', noSort: true },
        {
          name: "储能编号",
          value: "essId",
          noSort: true,
        },
        {
          name: "储能名称",
          value: "essName",
          noSort: true,
        },
        {
          name: "储能类型",
          value: "essType",
          noSort: true,
        },
        {
          name: "额定功率(kW)",
          value: "ratedP",
          noSort: true,
        },
        {
          name: "额定容量(kWh)",
          value: "capacity",
          noSort: true,
        },
        {
          name: "充/放电次数(次)",
          value: "chargeDischargeCount",
          noSort: true,
        },
        {
          name: "累计充电电量(kWh)",
          value: "chargeEnergyTotal",
          noSort: true,
        },
        {
          name: "累计放电电量(kWh)",
          value: "dischargeEnergyTotal",
          noSort: true,
        },
        {
          name: "所属变电站",
          value: "substationName",
          noSort: true,
        },
        {
          name: "所属馈线",
          value: "feederName",
          noSort: true,
        },
        // {
        //   name: '单机容量',
        //   value: 'singleMachineCap',
        //   noSort: true,
        //   formatter: (row) => (row.singleMachineCap ? `${row.singleMachineCap}MW` : ''),
        // },
        // { name: '机组编号', value: 'unitsNumber', noSort: true },
        // {
        //   // name: '一次调频实验方案',
        //   name: '快速频率响应试验方案',
        //   // value: "stationFileName",
        //   // order: 'stationFileId',
        //   order: 'fileId',
        //   noSort: true,
        //   type: 'linkPreview',
        //   // type1:'upload',
        //   clickPreview: this.dianji,
        //   clickDownload: this.doDownload,
        //   //clickUpload:this.doUpload
        // },
        // {
        //   // name: '实验方案上传时间',
        //   name: '上传时间',
        //   value: 'uploadTime',
        //   // noSort: true,
        //   formatter: (row) =>
        //     row.uploadTime ? row.uploadTime.replace('T', ' ') : '',
        // },
        // {
        //   name: '测试日期',
        //   value: 'testDate',
        //   // noSort: true,
        //   // formatter: (row) =>
        //   //   row.uploadTime
        //   //     ? row.uploadTime.replace("T", " ")
        //   //     : "",
        // },
        // {
        //   name: '测试序号',
        //   value: 'testNumber',
        //   noSort: true,
        // },
        // {
        //   name: '审核通过',
        //   value: 'isAudited',
        //   noSort: true,
        //   // fontColor: true,
        //   formatter: (row) =>
        //     yesOrNoList[row.isAudited] ? yesOrNoList[row.isAudited] : '',
        // },
        // {
        //   name: '审核时间',
        //   value: 'auditedTime',
        //   // noSort: true,
        //   formatter: (row) =>
        //     row.auditedTime ? row.auditedTime.replace('T', ' ') : '',
        // },
        // {
        //   name: '操作',
        //   value: 'result',
        //   noSort: true,
        //   type: 'check',
        //   order: 'id',
        //   clickCheck: this.dianji,
        //   // clickCopy: this.copyWindPower,
        //   // clickEdit: this.editWindPower,
        //   // clickDelete: this.deleteWindPower,
        //   // clickCheck: this.doCheck,
        // },
        // {
        //   name: '一次调频定值单',
        //   value: 'regulationReportForm',
        //   order: 'regulationReportFormId',
        //   noSort: true,
        //   type: 'linkPreview',
        //   clickPreview: this.doPreview,
        //   clickDownload: this.doDownload,
        // },
        // {
        //   name: '定值单上传时间',
        //   value: 'regulationTime2',
        //   noSort: true,
        //   formatter: (row) => (row.regulationReportForm ? row.regulationReportForm.createTime.replace('T', ' ') : ''),
        // },
        // {
        //   name: '是否滞后',
        //   value: 'isDelay',
        //   noSort: true,
        //   fontColor: true,
        //   formatter: (row) => (yesOrNoList[row.isDelay] ? yesOrNoList[row.isDelay] : ''),
        // },
      ],
      // 新增弹框显示
      dialogFormVisible: false,
      formLabelWidth: "80px",
      // 预览弹框f
      dialogVisible: false,
      paramData: [],
      checkList: [],
      checkId: "",
      queryParamStationId: "",
      showXLSX: false,
      xData: [
        "6月1日",
        "6月2日",
        "6月3日",
        "6月4日",
        "6月5日",
        "6月6日",
        "6月7日",
        "6月8日",
        "6月9日",
        "6月10日",
        "6月11日",
        "6月12日",
        "6月13日",
        "6月14日",
        "6月15日",
        "6月16日",
        "6月17日",
        "6月18日",
        "6月19日",
        "6月20日",
        "6月21日",
        "6月22日",
      ],
      // 变电站下拉列表
      stationOptions: [],
      // 馈线下拉列表
      lineOptions: [],
    };
  },

  mounted() {
    this.initEchart2();
    this.initEchart3();
  },
  created() {
    // this.regulationOrgList()
    // this.stationTypeList()
    // this.adjustRegulationList()
    // this.voltageLevelList()
    // this.getTreeData()
    this.getNowTime();
    this.getTreeData();
    this.queryFeeder();
    // this.queryStationTestNumber()
  },
  methods: {
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    submitForm() {
      this.$refs.windPowerTable.getDataInit();
    },

    // 、获取树结构
    getTreeData() {
      queryTreeData().then((res) => {
        if (res.resultCode === 0) {
          for (var i = 0; i < res.data.length; i++) {
            var obj = {};
            obj.label = res.data[i].substationName;
            obj.value = res.data[i].substationId;
          }
          console.log(obj);
          this.stationOptions.push(obj);
        }
      });
    },

    choose() {
      this.queryDetailParam.substationId = this.form.stationId;
      this.queryFeeder();
    },

    queryFeeder() {
      queryTreeData(this.queryDetailParam).then((res) => {
        if (res.resultCode === 0) {
          console.log(res.data);
          for (var i = 0; i < res.data.length; i++) {
            // let feedersList =  res.data[i].feeders;
            for (var x = 0; x < res.data[i].feeders.length; x++) {
              var obj = {};
              obj.label = res.data[i].feeders[x].name;
              obj.value = res.data[i].feeders[x].feederId;
              this.lineOptions.push(obj);
            }
          }
          console.log(obj);
        }
      });
    },

    dateFormat(val) {
      let date = new Date(val);
      let year = date.getFullYear();
      let month =
        date.getMonth() + 1 > 9
          ? date.getMonth() + 1
          : "0" + (date.getMonth() + 1);
      let day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();

      return year + "-" + month + "-" + day;
    },

    initEchart2() {
      let rq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
      let seriesArr = [];
      let list = [
        {
          name: "储能利用率",
          children: [
            44.84, 40.02, 51.64, 64.74, 54.69, 41.11, 59.68, 62.75, 61.21, 66.6,
            56.95, 68.19, 41.77, 50.67, 55.02, 56.62, 55.55, 40.87, 63.73,
            54.91, 43.36, 42.16, 63.36,
          ],
        },
        {
          name: "峰值利用率",
          children: [
            98.43, 89.98, 81.07, 96.68, 70.34, 71.35, 93.02, 73.43, 99.36,
            86.93, 70.65, 87.95, 77.44, 94.97, 88.92, 89.94, 77.19, 80.4, 93.07,
            94.0, 91.43, 86.28, 79.76,
          ],
        },
        {
          name: "低谷闲置率",
          children: [
            74.94, 80.06, 87.51, 95.46, 76.19, 87.87, 80.62, 74.2, 83.06, 74.61,
            85.32, 90.7, 93.64, 85.05, 95.92, 70.09, 91.55, 89.79, 77.32, 78.93,
            77.34, 80.76, 75.94,
          ],
        },
      ];
      let colorArr = ["0, 62, 246", "0, 193, 142", "253, 148, 67"];

      list.forEach((val, index) => {
        seriesArr.push({
          name: val.name,
          type: "line",
          symbolSize: 6,
          data: val.children,
          areaStyle: {
            normal: {
              color: this.$echarts.graphic.LinearGradient(
                0,
                0,
                0,
                1,
                [
                  {
                    offset: 0,
                    color: `rgba(${colorArr[index]},.2)`,
                  },
                  {
                    offset: 1,
                    color: "rgba(255, 255, 255,0)",
                  },
                ],
                false
              ),
            },
          },
          itemStyle: {
            normal: {
              color: `rgb(${colorArr[index]})`,
            },
          },
          lineStyle: {
            normal: {
              width: 2,
              shadowColor: `rgba(${colorArr[index]}, .2)`,
              shadowBlur: 4,
              shadowOffsetY: 25,
            },
          },
        });
      });

      let myChart = this.$echarts.init(document.getElementById("tafvr1"));
      let option = {
        backgroundColor: "#fff",
        tooltip: {
          trigger: "axis",
          axisPointer: {
            lineStyle: {
              color: "#ddd",
            },
          },
          backgroundColor: "rgba(255,255,255,1)",
          padding: [5, 10],
          textStyle: {
            color: "#000",
          },
        },
        legend: {
          // right: "center",
          top: "6%",
          left: "15%",
          textStyle: {
            color: "#000",
            fontSize: 12,
            // fontWeight: 600
          },
          data: list.map((val) => {
            return val.name;
          }),
        },
        grid: {
          left: "2%",
          right: "5%",
          bottom: "6%",
          top: "18%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: this.xData,
          boundaryGap: false,
          splitLine: {
            show: true,
            interval: "auto",
            lineStyle: {
              type: "dashed",
              color: ["#cfcfcf"],
            },
          },
          axisTick: {
            show: false,
          },
          axisLine: {
            lineStyle: {
              color: "#cfcfcf",
            },
          },
          axisLabel: {
            // margin: 10,
            textStyle: {
              fontSize: 12,
              color: "#9e9d9f",
              fontWeight: 600,
            },
          },
        },
        yAxis: [
          {
            name: "(%)",
            type: "value",
            splitLine: {
              show: true,
              lineStyle: {
                type: "dashed",
                color: ["#cfcfcf"],
              },
            },
            axisTick: {
              show: false,
            },
            axisLine: {
              show: true,
              lineStyle: {
                fontSize: 12,
                color: "#cfcfcf",
              },
            },
            axisLabel: {
              textStyle: {
                fontSize: 12,
                color: "#9e9d9f",
                fontWeight: 600,
              },
            },
            max: 100,
          },
        ],
        series: seriesArr,
      };
      myChart.setOption(option);
      window.addEventListener("resize", function () {
        myChart.resize();
      });
    },

    initEchart3() {
      let myChart = this.$echarts.init(document.getElementById("tafvr2"));
      let option = {
        backgroundColor: "#fff",
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
          },
        },
        grid: {
          left: "2%",
          right: "4%",
          bottom: "10%",
          top: "20%",
          containLabel: true,
        },
        legend: {
          data: ["充电量", "放电量"],
          top: "8%",
          textStyle: {
            // color: "#fff",
            fontSize: 16,
          },
          itemWidth: 12,
          itemHeight: 10,
          // itemGap: 35
        },
        xAxis: {
          type: "category",
          data: this.xData,
          axisLine: {
            lineStyle: {
              color: "#8c9493",
            },
          },
          axisLabel: {
            // interval: 0,
            // rotate: 40,
            textStyle: {
              fontFamily: "Microsoft YaHei",
              // fontWeight: 600,
              fontSize: 14,
            },
          },
        },

        yAxis: {
          name: "kWh",
          nameTextStyle: {
            // color: "#fff"
          },
          type: "value",
          axisLine: {
            show: true,
            lineStyle: {
              // color: '#8c9493'
            },
          },
          splitLine: {
            show: false,
            lineStyle: {
              color: "#8c9493",
            },
          },
          axisLabel: {
            textStyle: {
              // fontWeight: 600
            },
          },
        },
        series: [
          {
            name: "充电量",
            type: "bar",
            barWidth: "25%",
            itemStyle: {
              normal: {
                color: "rgb(76,197,176)",
              },
            },
            data: [
              1022.1, 847.2, 1088.85, 1422.6, 1101.15, 926.35, 1219.91, 1413.26,
              1353.12, 1474.37, 1193.5, 1434.2, 836.04, 1146.77, 1058.5,
              1112.67, 1170.23, 895.66, 1267.35, 1198.84, 997.93, 916.49,
              1210.7,
            ],
          },
          {
            name: "放电量",
            type: "bar",
            barWidth: "25%",
            itemStyle: {
              normal: {
                color: "rgb(177,221,168)",
              },
            },
            data: [
              1008.59, 826.23, 1184.94, 1472.19, 1242.32, 898.41, 1285.12,
              1295.01, 1341.51, 1333.04, 1184.04, 1528.39, 840.53, 1135.73,
              1249.02, 1120.0, 1191.93, 806.09, 1213.83, 1111.42, 929.45,
              821.16, 1324.56,
            ],
          },
        ],
      };
      myChart.setOption(option);
      window.addEventListener("resize", function () {
        myChart.resize();
      });
    },

    getNowTime() {
      // 获取当前日期
      var date = new Date();
      // 获取当前月份
      var nowMonth = date.getMonth() + 1;
      // 获取当前是几号
      var strDate = date.getDate();
      // 添加分隔符“-”
      var seperator = "-";
      // 对月份进行处理，1-9月在前面添加一个“0”
      if (nowMonth >= 1 && nowMonth <= 9) {
        nowMonth = "0" + nowMonth;
      }
      // 对月份进行处理，1-9号在前面添加一个“0”
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      // 最后拼接字符串，得到一个格式为(yyyy-MM-dd)的日期
      this.queryDetailParam.testDate =
        date.getFullYear() + seperator + nowMonth + seperator + strDate;
    },
    // 获取渲染树的数据
    // getTreeData(data) {
    //   queryOfExperimentalresults(data).then((res) => {
    //     this.dataTree = addStationName(res.data);
    //     // console.log(data.stationId+"111111");
    //     this.$nextTick(function () {
    //       if (data == undefined) {
    //         this.$refs.equipmentTree.setCheckedKeys([]);
    //         this.checkList = [];
    //         this.queryParamStationId = "";
    //       } else {
    //         this.$refs.equipmentTree.setCheckedKeys([data.stationId], false);
    //         let list = [data.stationId];
    //         this.queryParamStationId = data.stationId;
    //         console.log(list);
    //         this.checkList = list;

    //         let params = {
    //           regulationOrgIds: [],
    //           stationIds: list,
    //           fileSort: "01",
    //         };
    //         this.queryDetailParam = params;
    //         params.stationIds.forEach((e, i) => {
    //           // console.log(params.regulationOrgIds.includes(getAllParentNodes(this.dataTree,e)[0].id))
    //           if (
    //             params.regulationOrgIds.includes(
    //               getAllParentNodes(this.dataTree, e)[0].id
    //             )
    //           ) {
    //             // 找到这个元素删掉他
    //             this.queryDetailParam.stationIds =
    //               this.queryDetailParam.stationIds.filter((d) => d !== e);
    //           }
    //         });
    //         this.$nextTick(() => {
    //           this.$refs.windPowerTable.getDataInit();
    //         });
    //       }
    //     });
    //   });
    // },
    // 下拉框change事件
    inputChange(val) {
      // console.log(val, "搜索下拉框val");
      // console.log(this.$refs.equipmentTree.queryInputListCopy, "搜索下拉框val");
      let param = {
        stationId: val,
      };
      this.getTreeData(param);
    },
    // 点击树的勾选框
    handleCheck(checkedKeys, e) {
      if (this.queryParamStationId !== "") {
        console.log("有查询条件");
        let params = {
          regulationOrgIds: [],
          stationIds: [],
          fileSort: "01",
        };

        if (e.checkedKeys[1]) {
          params.stationIds.push(e.checkedKeys[1]);
        }
        this.queryDetailParam = params;
      } else {
        console.log("无查询条件");
        let nodeList = this.$refs.equipmentTree.getCheckedNodes();
        let params = {
          regulationOrgIds: [],
          stationIds: [],
          fileSort: "01",
        };
        nodeList
          .filter((e) => e.level !== "3")
          .forEach((item) => {
            if (item.level === "1") {
              params.regulationOrgIds.push(item.id);
            }
            if (item.level === "2") {
              params.stationIds.push(item.id);
            }
          });
        this.queryDetailParam = params;
        params.stationIds.forEach((e, i) => {
          if (
            params.regulationOrgIds.includes(
              getAllParentNodes(this.dataTree, e)[0].id
            )
          ) {
            // 找到这个元素删掉他
            this.queryDetailParam.stationIds =
              this.queryDetailParam.stationIds.filter((d) => d !== e);
          }
        });
      }
      this.$nextTick(() => {
        this.$refs.windPowerTable.getDataInit();
      });
    },
    // 处理三级节点之间勾选联动
    checkChange(row, col, check) {
      //console.log(this.dataTree, "this.dataTree");
      if (row.level == "3") {
        // console.log(row, col, check, "row, col");
        let checkedKeys = findSiblingIds(this.dataTree, row.id);
        // console.log(checkedKeys,'checkedKeyscheckedKeys')
        checkedKeys.forEach((item) => {
          this.$refs.equipmentTree.setChecked(item.id, col);
        });
      }
    },

    // 总调下拉框的数据
    async regulationOrgList() {
      await regulationOrgList().then((res) => {
        if (res.code === "000000") {
          this.dispatchList = res.data;
        }
      });
    },

    // 上下调投入分类下拉框的数据
    async adjustRegulationList() {
      await adjustRegulationList().then((res) => {
        if (res.code === "000000") {
          this.adjustRegulationLists = res.data;
        }
      });
    },
    // 场站类型下拉框的数据
    async stationTypeList() {
      await stationTypeList().then((res) => {
        if (res.code === "000000") {
          this.stationTypeLists = res.data;
        }
      });
    },
    // 电压等级下拉框的数据
    async voltageLevelList() {
      await voltageLevelList().then((res) => {
        if (res.code === "000000") {
          this.voltageLevelLists = res.data;
        }
      });
    },

    // 测试序号下拉
    async queryStationTestNumber() {
      await queryStationTestNumber(this.queryDetailParam).then((res) => {
        if (res.code === "000000") {
          this.testNumberList = res.data;
        }
      });
    },

    // 测试日期
    testDateChange(val) {
      if (val) {
        this.$set(this.queryDetailParam, "testNumber", "");
        this.queryStationTestNumber();
      }
    },
    // 新增弹框
    addWindPower() {
      this.id++;
      // this.operate === "add";
      this.$set(this, "operate", "add");
      this.dialogFormVisible = true;
      this.addDialogVisibleTitle = "新增";
      this.getFrom = { regulationOrgId: "1", caseIsAudited: "" };
      console.log(this.getFrom);
    },

    // 获取表格多行选中的数据  点击行选中
    getMultipleSelection2(row) {
      this.tableData = JSON.parse(JSON.stringify(row));
      this.tableData.forEach((element) => {
        this.getFrom = element;
      });
    },

    getMultipleSelection() {
      this.tableData = JSON.parse(
        JSON.stringify(this.$refs.windPowerTable.multipleSelection)
      );
      this.tableData.forEach((element) => {
        this.getFrom = element;
      });
    },

    // 编辑
    editWindPower(row) {
      console.log(row);
      if (row) {
        this.$set(this, "operate", "edit");
        this.getMultipleSelection2([row]);
        this.dialogFormVisible = true;
        this.addDialogVisibleTitle = "编辑";
        return true;
      } else {
        this.operate = "edit";
        this.getMultipleSelection();
        if (this.tableData && this.tableData.length < 1) {
          Message.warning("请先勾选要编辑的数据");
        } else if (this.tableData && this.tableData.length > 1) {
          Message.warning("编辑的时候只能选择一条数据,请重新选择");
          return false;
        } else {
          this.addDialogVisibleTitle = "编辑";
          this.dialogFormVisible = true;
          // this.$nextTick(()=>{
          // this.$refs.childRules.$refs.stationRefEdit.value=this.getFrom.stationName
          // })
          return true;
        }
      }
    },

    // 复制
    copyWindPower(row) {
      // this.operate = "copy";
      this.$set(this, "operate", "copy");
      // this.getMultipleSelection();
      this.getMultipleSelection([row]);

      if (this.tableData && this.tableData.length < 1) {
        Message.warning("请先勾选要复制的数据");
      } else if (this.tableData && this.tableData.length > 1) {
        Message.warning("复制的时候只能选择一条数据,请重新选择");
        return false;
      } else {
        this.addDialogVisibleTitle = "复制";
        // 复制的时候清空所有的文件上传
        this.getFrom.regulationReportForm = "";
        this.getFrom.regulationTestPlan = "";
        this.getFrom.regulationTestReport = "";
        this.getFrom.responsePlan = "";
        this.getFrom.responseReport = "";
        this.dialogFormVisible = true;
        return true;
      }
    },

    // 删除
    deleteWindPower(row) {
      if (row) {
        this.$confirm("是否确认删除？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          // 发送请求
          let params = [row.stationFileId];
          // 发送请求
          // deleteStationFile({stationFileId:row.stationFileId}).then((res) => {
          deleteStationFile(params).then((res) => {
            if (res.code === "000000") {
              Message.success("删除成功");
              this.$refs.windPowerTable.getDataInit();
            }
          });
        });
      } else {
        if (this.$refs.windPowerTable.multipleSelection.length === 0) {
          Message.warning("请选择要删除的数据");
          return;
        }
        // 确认删除嘛
        this.$confirm("是否确认删除？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          // 发送请求
          let params = this.$refs.windPowerTable.multipleSelection.map(
            (item) => item.stationFileId
          );
          //let params = [row.stationId]
          // 发送请求
          // deleteStationFile({stationFileId:row.stationFileId}).then((res) => {
          deleteStationFile(params).then((res) => {
            if (res.code === "000000") {
              Message.success("删除成功");
              this.$refs.windPowerTable.getDataInit();
            }
          });
        });
      }
    },

    // 检索
    searchList() {
      this.$refs.windPowerTable.getDataInit();
    },
    // 重置
    // resetSearchList() {
    //   for (let key in this.queryDetailParam) {
    //     this.queryDetailParam[key] = ''
    //   }
    //   this.queryDetailParam.stationType = '7'
    //   this.$refs.windPowerTable.getDataInit()
    // },

    // 详情重置
    resetCon() {
      this.getFrom = {};
      if (this.$refs.childRules.$refs.owner) {
        this.$refs.childRules.$refs.owner.labels = "";
      }
      if (this.$refs.childRules.$refs.testingUnit) {
        this.$refs.childRules.$refs.testingUnit.labels = "";
      }
    },

    // 下载
    async doDownload(row, col, name) {
      let excelName = `${name}`;
      // const res = await getPdf(row[`${col}Id`]);
      const res = await getPdf(row.stationFileId);
      const fileType = row.stationFileName.substring(
        row.stationFileName.lastIndexOf(".") + 1
      );
      // if (
      //   res.fileType === "pdf" &&
      //   res.fileType === "xlsx" &&
      //   res.fileType === "xls" &&
      //   res.fileType === 'doc' &&
      //   res.fileType === 'docx'
      // ) {
      //   this.$message.warning("只支持pdf与excel格式的文件下载");
      //   return;
      // }
      let typeList = {
        pdf: "application/pdf",
        xls: "application/vnd.ms-excel",
        xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        doc: "application/msword",
        docx: "application/msword",
      };
      const link = document.createElement("a");
      let blob = new Blob([res], {
        type: typeList[fileType],
      });
      // xlsx的文件type

      link.style.display = "none";
      link.href = URL.createObjectURL(blob);
      link.download = excelName; //下载的文件名
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },

    // async downloadWin() {
    //   let excelName = '频率响应试验方案列表.xlsx'
    //   const res = await downloadStationTestInfo(this.queryDetailParam)
    //   const link = document.createElement('a')
    //   let blob = new Blob([res], {
    //     type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    //   })
    //   link.style.display = 'none'
    //   link.href = URL.createObjectURL(blob)
    //   link.download = excelName //下载的文件名
    //   document.body.appendChild(link)
    //   link.click()
    //   document.body.removeChild(link)
    // },

    async downloadWin() {
      exportFn(
        "频率响应试验方案列表.xlsx",
        downloadStationTestInfo,
        this.queryDetailParam
      );
    },

    //  导出
    exportExcel() {
      this.downloadWin();
    },

    // 预览
    // async doPreview(row, col) {
    //   let doc = require("docx-preview");
    //   // const res = await getPdf(row[`${col}Id`]);
    //   const res = await getPdf(row.stationFileId);
    //   let fileType=''
    //   if(row && row.stationFileName){
    //      fileType = row.stationFileName.substring(row.stationFileName.lastIndexOf(".")+1);
    //      console.log(fileType);
    //   }
    //   // if (
    //   //   res.fileType !== "pdf" &&
    //   //   res.fileType !== "xlsx" &&
    //   //   res.fileType !== "xls" &&
    //   //   res.fileType === 'doc' &&
    //   //   res.fileType === 'docx'
    //   // ) {
    //   //   // this.$message.warning("只支持pdf与excel格式的文件预览！！！");
    //   //   return;
    //   // }
    //   let typeList = {
    //     pdf: "application/pdf",
    //     xls: "application/vnd.ms-excel",
    //     xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    //     doc:"application/msword",
    //     docx:"application/msword",
    //   };
    //   const blob = new Blob([res], { type: typeList[fileType] });
    //   if (fileType === "pdf") {
    //     this.pdf = URL.createObjectURL(blob);
    //   } else if(fileType === "xls" || fileType === "xlsx"){
    //     const reader = new FileReader();
    //     reader.onload = (e) => {
    //       const data = new Uint8Array(e.target.result);
    //       let workbook = XLSX.read(data, { type: "array" }); // 解析数据
    //       this.tableToHtml(workbook);
    //     };
    //     reader.readAsArrayBuffer(blob);
    //   }else{
    //     this.$nextTick(()=>{
    //       doc.renderAsync(blob, document.querySelector("#tableHtml")); // 渲染到页面
    //     })
    //   this.dialogPreVisible = true;
    // }},

    openMethods() {
      this.doPreview(this.row);
    },

    dianji(row) {
      this.row = row;
      console.log("??/");
      this.dialogVisible = true;
      // this.key++
    },

    async doPreview(row, col) {
      //const res = await getPdf(row[`${col}Id`]);
      const doc = require("docx-preview");
      const res = await getPdf(row.stationFileId);
      let fileType = "";
      if (row && row.stationFileName) {
        fileType = row.stationFileName.substring(
          row.stationFileName.indexOf(".") + 1
        );
      }
      // if (
      //   res.fileType !== "pdf" &&
      //   res.fileType !== "xlsx" &&
      //   res.fileType !== "xls" &&
      //res.fileType === 'doc' &&
      //   res.fileType === 'docx'
      // ) {
      //   this.$message.warning("只支持pdf与excel格式的文件预览");
      //   return;
      // }
      let typeList = {
        pdf: "application/pdf",
        xls: "application/vnd.ms-excel",
        xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        doc: "application/msword",
        docx: "application/msword",
      };
      const blob = new Blob([res], { type: typeList[fileType] });
      if (fileType === "pdf") {
        this.pdf = URL.createObjectURL(blob);
      } else if (fileType === "doc" || fileType === "docx") {
        doc.renderAsync(blob, document.querySelector("#tableHtml")); // 渲染到页面
      } else {
        const reader = new FileReader();
        reader.onload = (e) => {
          const data = new Uint8Array(e.target.result);
          let workbook = XLSX.read(data, { type: "array" }); // 解析数据
          this.tableToHtml(workbook);
        };
        reader.readAsArrayBuffer(blob);

        // this.showXLSX = true;
        // const file = new window.File(
        //   [blob], // blob
        //   '快速频率响应试验方案.xlsx',
        //   { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }
        // );
        // console.log("====file====", file)
        // this.uploadExcel1(file)
      }
      this.dialogPreVisible = true;
    },

    uploadExcel1(files) {
      // In some cases, you need to use $nextTick
      // this.$nextTick(() => {})
      console.log(luckysheet);
      // LuckyExcel.setWorkBookReadOnly()
      LuckyExcel.transformExcelToLucky(
        files,
        function (exportJson, luckysheetfile) {
          console.log("transformExcelToLucky", files, exportJson);
          if (exportJson.sheets == null || exportJson.sheets.length == 0) {
            alert(
              "Failed to read the content of the excel file, currently does not support xls files!"
            );
            return;
          }
          window.luckysheet.destroy();
          window.luckysheet.create({
            container: "luckysheet", //luckysheet is the container id
            showinfobar: false,
            data: exportJson.sheets,
            title: exportJson.info.name,
            userInfo: exportJson.info.name.creator,
            lang: "zh", // 设定表格语言
            showinfobar: true, //是否显示顶部信息栏
            showtoolbar: false, //是否显示工具栏
            // showsheetbar: false,//是否显示底部sheet页按钮
            enableAddRow: false, //允许添加行
            readOnly: true,
          });
        }
      );
    },

    tableToHtml(workbook) {
      var worksheet = workbook.Sheets[workbook.SheetNames[0]];
      console.log(worksheet, "worksheet");
      // var innerHTML = XLSX.utils.sheet_to_html(worksheet);
      if (document.querySelector("#tableHtml")) {
        document.querySelector("#tableHtml").innerHTML =
          XLSX.utils.sheet_to_html(worksheet);
        document.querySelector(".table-html-wrap table");
        let trs = document.querySelectorAll("tr");
        trs.forEach((tr) => {
          if (!tr.innerText.trim()) {
            tr.remove();
          }
        });
        document.querySelector(".el-dialog__body").style.overflowX = "auto";
      }
      let tds = document.querySelectorAll("td");
    },
    // 保存
    saveForm() {
      // 校验
      let flag = this.$refs["childRules"].validateForm();

      if (flag) {
        // 已有审核通过的试验方案
        if (this.addDialogVisibleTitle == "新增") {
          if (
            this.getFrom.caseIsAudited == 1 &&
            this.$refs.childRules.stationAuditedFiles &&
            this.$refs.childRules.stationAuditedFiles.length > 0
          ) {
            this.$confirm(
              "该次测试已有审核通过的试验方案，是否替换？",
              "提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }
            ).then(() => {
              this.insertOrUpdateStationInfoFile();
              this.dialogFormVisible = false;
            });
          } else {
            this.insertOrUpdateStationInfoFile();
            this.dialogFormVisible = false;
          }
        }
        if (this.addDialogVisibleTitle == "编辑") {
          this.updateStationFileWarn();
        }
        // this.insertOrUpdateStationInfoFile()
        // this.dialogFormVisible = false
      } else {
        return;
      }
    },

    // 首先封装参数（对象）转换为formData格式
    // getFormData(object) {
    //   const formData = new FormData();
    //   Object.keys(object).forEach((key) => {
    //     const value = object[key];
    //     if (Array.isArray(value)) {
    //       value.forEach((subValue, i) => {
    //         formData.append(key + `[${i}]`, subValue);
    //       });
    //     } else {
    //       formData.append(key, object[key]);
    //     }
    //   });
    //   return formData;
    // },

    // 首先封装参数（对象）转换为formData格式

    getFormData() {
      let form = this.$refs.childRules;
      // 文件存在就append,不存在就不append,不往后台传递这个字段
      form.fileList1[0] &&
        this.formData.set("regulationReportForm", form.fileList1[0].raw);
      form.fileList2[0] &&
        this.formData.set("regulationTestPlan", form.fileList2[0].raw);
      form.fileList3[0] &&
        this.formData.set("regulationTestReport", form.fileList3[0].raw);
      form.fileList4[0] &&
        this.formData.set("responsePlan", form.fileList4[0].raw);
      form.fileList5[0] &&
        this.formData.set("responseReport", form.fileList5[0].raw);
      // this.formData.set(
      //   "regulationTestPlanId",
      //   this.getFrom.regulationTestPlanId
      //     ? this.getFrom.regulationTestPlanId
      //     : null
      // );
      // this.formData.set(
      //   "regulationTestPlanId",
      //   this.getFrom.stationFileId
      //     ? this.getFrom.stationFileId
      //     : null
      // );
      this.formData.set(
        "regulationOrgId",
        this.getFrom.regulationOrgId ? this.getFrom.regulationOrgId : null
      );
      this.formData.set(
        "stationName",
        this.getFrom.stationName ? this.getFrom.stationName : null
      );
      this.formData.set(
        "voltageLevelCode",
        this.getFrom.voltageLevelCode ? this.getFrom.voltageLevelCode : ""
      );
      this.getFrom.stationName &&
        this.formData.set("stationName", this.getFrom.stationName);
      this.formData.set("ownersName", this.getFrom.ownersName);
      this.formData.set("isProduction", this.getFrom.isProduction);
      this.formData.set("stationCap", this.getFrom.stationCap);
      this.formData.set("isRegulation", this.getFrom.isRegulation);
      this.formData.set("productionTime", this.getFrom.productionTime);
      // 测试日期
      this.formData.set("testDate", this.getFrom.testDate);
      // 测试序号
      this.formData.set("testNumber", this.getFrom.testNumber);
      if (
        this.getFrom.regulationTime === undefined ||
        this.getFrom.regulationTime === null
      ) {
        delete this.getFrom.regulationTime;
      } else {
        this.formData.set("regulationTime", this.getFrom.regulationTime);
      }
      //this.getFrom.regulationTime && this.formData.set('regulationTime', this.getFrom.regulationTime.replace('T', ' '))
      this.formData.set("unRegulateReason", this.getFrom.unRegulateReason);
      // 上调/下调是否投入
      this.formData.set(
        "adjustRegulationCode",
        this.getFrom.adjustRegulationCode
      );
      if (
        this.getFrom.isResponse === undefined ||
        this.getFrom.isResponse === null
      ) {
        delete this.getFrom.isResponse;
      } else {
        this.formData.set("isResponse", this.getFrom.isResponse);
      }

      this.getFrom.deadZone &&
        this.formData.set("deadZone", this.getFrom.deadZone);
      this.getFrom.adjustRatio &&
        this.formData.set("adjustRatio", this.getFrom.adjustRatio);
      this.getFrom.startingPowerThreshold &&
        this.formData.set(
          "startingPowerThreshold",
          this.getFrom.startingPowerThreshold
        );
      this.getFrom.lowerLimit &&
        this.formData.set("lowerLimit", this.getFrom.lowerLimit);
      this.getFrom.powerAdjustDeviation &&
        this.formData.set(
          "powerAdjustDeviation",
          this.getFrom.powerAdjustDeviation
        );
      this.getFrom.upLimit &&
        this.formData.set("upLimit", this.getFrom.upLimit);
      this.getFrom.startTime &&
        this.formData.set("startTime", this.getFrom.startTime);
      this.getFrom.responseTime &&
        this.formData.set("responseTime", this.getFrom.responseTime);
      this.getFrom.adjustTime &&
        this.formData.set("adjustTime", this.getFrom.adjustTime);
      // 一次调频投退功能
      this.getFrom.onOffFunction &&
        this.formData.set("onOffFunction", this.getFrom.onOffFunction);
      this.getFrom.isUpFunction &&
        this.formData.set("isUpFunction", this.getFrom.isUpFunction);
      this.getFrom.isLowerFunction &&
        this.formData.set("isLowerFunction", this.getFrom.isLowerFunction);
      this.getFrom.isResponseFunction &&
        this.formData.set(
          "isResponseFunction",
          this.getFrom.isResponseFunction
        );
      this.getFrom.agcControl &&
        this.formData.set("agcControl", this.getFrom.agcControl);
      this.getFrom.maxUpdownPower &&
        this.formData.set("maxUpdownPower", this.getFrom.maxUpdownPower);
      this.getFrom.adjustSpeed &&
        this.formData.set("adjustSpeed", this.getFrom.adjustSpeed);
      this.getFrom.maxUpdownPowerDuration &&
        this.formData.set(
          "maxUpdownPowerDuration",
          this.getFrom.maxUpdownPowerDuration
        );
      // 主动测试
      this.getFrom.activeTestNum &&
        this.formData.set("activeTestNum", this.getFrom.activeTestNum);
      this.getFrom.qualifiedNum &&
        this.formData.set("qualifiedNum", this.getFrom.qualifiedNum);
      this.getFrom.qualifiedRatio &&
        this.formData.set("qualifiedRatio", this.getFrom.qualifiedRatio);
      this.getFrom.caseIsAudited &&
        this.formData.set(
          "caseIsAudited",
          this.getFrom.caseIsAudited ? this.getFrom.caseIsAudited : ""
        );
      this.getFrom.caseAuditTime &&
        this.formData.set("caseAuditTime", this.getFrom.caseAuditTime);
      this.getFrom.reportIsAudited &&
        this.formData.set("reportIsAudited", this.getFrom.reportIsAudited);
      this.getFrom.reportAuditTime &&
        this.formData.set("reportAuditTime", this.getFrom.reportAuditTime);

      // 区分新增或者删除的时候传参
      if (this.operate === "add" || this.operate === "copy") {
        let queryInputList = form.queryInputList;

        let stationId = queryInputList.filter(
          (item) => item.label === form.detailForm.stationName
        )[0].value;

        this.formData.set("operateCode", "1");
        this.formData.set("stationType", "7");
        this.formData.set("stationId", stationId);

        if (form.fileList2[0] == undefined) {
          this.formData.delete("regulationTestPlan");
        }

        if (
          this.getFrom.caseIsAudited == undefined ||
          this.getFrom.caseIsAudited == null ||
          this.getFrom.caseIsAudited == ""
        ) {
          this.formData.delete("caseIsAudited");
        }

        if (this.getFrom.caseAuditTime == undefined) {
          this.formData.delete("caseAuditTime");
        }
      }

      if (this.operate === "edit") {
        let queryInputList = form.queryInputList;

        let stationId = queryInputList.filter(
          (item) => item.label === form.detailForm.stationName
        )[0].value;
        this.formData.set("operateCode", "2");
        this.formData.set("stationId", form.detailForm.stationId);
        // this.formData.set("regulationId", form.detailForm.regulationId);
        this.formData.set(
          "regulationTestPlanId",
          this.getFrom.stationFileId ? this.getFrom.stationFileId : null
        );
        this.formData.set("stationType", "7");

        if (form.fileList2[0] == undefined) {
          this.formData.delete("regulationTestPlan");
        }

        if (
          this.getFrom.caseIsAudited == undefined ||
          this.getFrom.caseIsAudited == null ||
          this.getFrom.caseIsAudited == ""
        ) {
          this.formData.delete("caseIsAudited");
        }

        if (this.getFrom.caseAuditTime == undefined) {
          this.formData.delete("caseAuditTime");
        }
      }

      return this.formData;
    },

    // 新增
    async insertOrUpdateStationInfoFile() {
      this.formData = this.getFormData();
      this.formData.set("ownersId", this.$refs.childRules.$refs.owner.labels);
      this.formData.set("stationName", this.getFrom.stationName);
      this.formData.set("fileSort", "01");
      await insertStationInfoFile(this.formData).then((res) => {
        if (res.code === "000000") {
          Message.success(`${this.addDialogVisibleTitle}成功`);
          this.$refs.windPowerTable.getDataInit();
        }
      });
    },

    // 编辑电厂文件-测试方案/结果  弹窗提醒
    async updateStationFileWarn() {
      this.formData = this.getFormData();
      this.formData.set("ownersId", this.$refs.childRules.$refs.owner.labels);
      this.formData.set("stationName", this.getFrom.stationName);
      this.formData.set("fileSort", "01");
      await updateStationFileWarn(this.getFormData(this.formData)).then(
        (res) => {
          console.log(res, "111111");
          if (res.code === "000000") {
            if (res.data == true) {
              this.updateStationInfoFile();
              this.dialogFormVisible = false;
            } else {
              this.$confirm(
                "该次测试已有审核通过的试验方案，是否替换？",
                "提示",
                {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                }
              ).then(() => {
                this.updateStationInfoFile();
                this.dialogFormVisible = false;
              });
            }
          }
        }
      );
    },

    // 修改
    async updateStationInfoFile() {
      this.formData = this.getFormData();
      this.formData.set("ownersId", this.$refs.childRules.$refs.owner.labels);
      this.formData.set("stationName", this.getFrom.stationName);
      this.formData.set("fileSort", "01");
      await updateStationInfoFile(this.getFormData(this.formData)).then(
        (res) => {
          if (res.code === "000000") {
            Message.success(`${this.addDialogVisibleTitle}成功`);
            this.$refs.windPowerTable.getDataInit();
          }
        }
      );
    },

    //列表查看，跳转到新型资源快速频率响应主动测试页面
    doCheck() {
      this.$router.push({ path: "/windPower", query: { stationId: "001" } });
      console.log(this.$route.path, "222");
      // this.$router.push({ name: 'home', params: { id: '001' } })
    },

    // 最外部检索按钮
    searchOrder() {
      this.$nextTick(() => {
        this.$refs.windPowerTable.getDataInit();
      });
    },
    // 检索重置
    resetSearchList() {
      // for (let key in this.queryDetailParam) {
      //   this.queryDetailParam[key] = ''
      // }
      this.queryDetailParam.testDate = "";
      this.queryDetailParam.testNumber = "";
      this.queryDetailParam.isAudited = "";
      this.$refs.windPowerTable.getDataInit();
    },

    handleClear() {
      this.getTreeData();
    },
  },
};
